import styles from './index.less';
import React, { useState, useEffect } from 'react';
import { CloseOutlined } from '@ant-design/icons';
import { Tabs, message } from 'antd';
import { connect, history } from 'umi';
import { ImuneTreeArr } from '@/types/common';
import actions from '@/shared/actions';

const PageTabs = (props: any) => {
  const { common } = props;

  /**
   * 页签切换选择
   * @param index 下标索引
   */
  const onChangeFn = (index: string) => {
    // 查询当前项在总菜单数组里的位置
    const Zindex = common?.menuTreeList?.findIndex((item: ImuneTreeArr) => item.id === common?.menubar[index].id);

    props.dispatch({
      type: 'common/save',
      payload: {
        numberZindex: index,
        defaultSelected: [`${Zindex+1}`]
      },
    });
    history.push(common?.menubar[index].path);
    actions.setGlobalState({
      // 当前路径
      activePath: '',
    });
  };

  /**
    * 菜单删除
    * @param index 选中数组下标
    * @returns
    */
  const delMenuBar = (index: number) => {
    const menuBarArr = [...common?.menubar];
    if (menuBarArr.length === 1) {
      message.info('已是最后一项');
      return;
    }
    menuBarArr.splice(index, 1);

    // 删除的是第一项那么选中项往后推 不是则 往前推
    const arrIndex = index === 0 ? 0 : index - 1; // 获取删除的前一个下标索引
    // 查询当前项在总菜单数组里的位置
    const Zindex = common?.menuTreeList?.findIndex((item: ImuneTreeArr) => item.id === common?.menubar[arrIndex].id);

    props.dispatch({
      type: 'common/save',
      payload: {
        numberZindex: arrIndex,
        menubar: [...menuBarArr],
        defaultSelected: [`${Zindex+1}`]
      },
    });

    actions.setGlobalState({
      // 当前路径
      activePath: '',
    });

    // 跳转都删除操作之后应该跳转的页面
    history.push(menuBarArr[arrIndex].path);
  };

  return (
    <div className={styles.box}>
      <Tabs
        onChange={onChangeFn}
        activeKey={common.numberZindex}
        items={common.menubar.map((item: ImuneTreeArr, index: number) => {
          return {
            label: (
              <span>
                {`${item.title} `}
                <CloseOutlined onClick={() => { delMenuBar(index) }} />
              </span>
            ),
            key: index
          };
        })}
      />
    </div>
  );
};

export default connect(({ common }: any) => ({ common }))(PageTabs);
